package org.syx.droid.telnet.test;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

/**
 * This is the Service that {@link SocketTestActivity} calls to start the
 * network module. Although this runs on the UI thread, this will create a new
 * worker thread in which a {@link TelnetServer} will run.
 * 
 * I couldn't think of a more appropriate name, so I used `MasterController`,
 * even if it doesn't really control anything.
 * 
 * @author cesardepadua
 * 
 */
public class MasterController extends Service {
	private Thread telnetServerThread = null;
	
	private Handler handler;
	
	/**
	 * This {@link Service} isn't meant to be bound.
	 */
	@Override
	public IBinder onBind (Intent intent) {
	
		return null;
	}
	
	/**
	 * Get the instance of {@link TelnetServer}, and run it on an execution
	 * thread, separate from the UI thread. Any exceptions will be printed to
	 * logcat.
	 * 
	 * @return {@link Service.START_NOT_STICKY}
	 */
	@Override
	public int onStartCommand (Intent intent, int flags, int startId) {
	
		this.handler = new Handler ();
		
		if (telnetServerThread == null) {
			Log.i ("MasterController", "Creating a new Thread");
			
			telnetServerThread = new Thread (TelnetServer.getInstance (this.handler, 1089));
			telnetServerThread.start ();
			
			Log.i ("MasterController", "New Thread created.");
		} else {
			Log.i ("MasterController",
					"TelnetServer has already been instantiated");
		}
		
		return Service.START_NOT_STICKY;
	}
}
